package com.y2020.d0108;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * @author 歪大哥😁
 * @date 2020-01-08.
 */
public class ReferenceStudy {

    static class ReferenceTest {
        static final int _1M = 1024 * 1024 ;

        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();

        void testStrongReference() {
            ArrayList<byte[]> strongReference = new ArrayList<>();
            try {
                while (true) {
                    strongReference.add(new byte[_1M]);
                }
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }

        void testSoftReference() {
            ArrayList<SoftReference> softReferences = new ArrayList<>();
            try {
                while (true) {
                    SoftReference temp = new SoftReference(new byte[_1M], referenceQueue);
                    Reference<?> poll;
                    while ((poll = referenceQueue.poll()) != null) {
                        System.out.println(poll);
                    }
                    System.out.println("创建对象[" + temp.toString() + "]");
                    softReferences.add(temp);
                }
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }

        void testWeakReference() {
            ArrayList<WeakReference> weakReferences = new ArrayList<>();
            try {
                while (true) {
                    weakReferences.add(new WeakReference(new byte[_1M], referenceQueue));
                }
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }

        void testPhantomReference() {
            ArrayList<PhantomReference<byte[]>> phantomReferences = new ArrayList<>();
            try {
                while (true) {
                    phantomReferences.add(new PhantomReference<>(new byte[_1M], referenceQueue));
                }
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ReferenceTest test = new ReferenceTest();
        test.testSoftReference();
    }


}
